package com.baoy.cloud.xxx.sso.web;

import com.baoy.cloud.xxx.common.Captcha;
import com.baoy.cloud.xxx.common.Constant;
import com.baoy.cloud.xxx.common.JSONResult;
import com.baoy.cloud.xxx.common.ex.Exceptions;
import com.baoy.cloud.xxx.common.utils.CookieUtil;
import com.baoy.cloud.xxx.sso.dto.UserDTO;
import com.baoy.cloud.xxx.sso.shiro.session.SerializableUtils;

import com.baoy.cloud.xxx.sso.utils.SsoLoginHelper;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @ResponseBody
    @PostMapping("/login")
    public JSONResult executeLogin(@Validated UserDTO userDTO, HttpServletResponse response,
            String backurl) {
        JSONResult retjson = null;
        UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getUsername(),
                userDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String sessionId = session.getId().toString();
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            retjson = JSONResult.writeFailure(Exceptions.username_notfound);
            log.error("{}", e);
        } catch (IncorrectCredentialsException e) {
            retjson = JSONResult.writeFailure(Exceptions.password_error);
            log.error("{}", e);
        } catch (LockedAccountException e) {
            retjson = JSONResult.writeFailure(Exceptions.username_locked);
            log.error("{}", e);
        }
        if (retjson == null) {
            retjson = JSONResult.writeSuccess(Exceptions.login_success);
            retjson.setData(StringUtils.isBlank(backurl) ? "/" : backurl);
            SsoLoginHelper.login(response, sessionId, session);
            log.info("::用户{}成功登录进入系统>>>", userDTO);
        }
        return retjson;
    }

    @GetMapping({"/", "/index"})
    public String index() {
        return "index";
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, HttpSession session) {
        try {
            Captcha captcha = new Captcha(98, 30);
            session.setAttribute(Constant.CAPTCHA, captcha.getCode());
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
